use std::any::Any;
use std::env::var;
use pyo3::prelude::*;
use pyo3::types::PyDict;
use hashbrown::HashMap;

#[pyfunction]
fn sum_as_string(a: usize, b: usize) -> PyResult<String> {
    Ok((a + b).to_string())
}

#[pyfunction]
fn test_res(x: Vec<i32>) -> PyResult<Vec<i32>> {
    Ok(x)
}

fn min(a: i32, b: i32) -> i32 {
    if a < b { a } else { b }
}

fn max(a: i32, b: i32) -> i32 {
    if a > b { a } else { b }
}

// # 查寻所有的网格自由边 🍕
// # 🍕 引用计数法 🍕
// # version 0.0.1
#[pyfunction]
fn search_free_edge_cell(
    element_id_to_index_map: &Bound<'_, PyDict>,
    cell_index_to_point_index_map: &Bound<'_, PyDict>,
) -> Vec<Vec<String>> {
    let mut line_map: HashMap<String,[i32; 2]> = HashMap::new();
    let mut result_free_edge:Vec<String> = Vec::new();   //
    let mut result_share_edge:Vec<String> = Vec::new();
    let mut result_t_edge:Vec<String> = Vec::new();
    let mut flag = 0;
    for (key, value) in cell_index_to_point_index_map.iter() {
        let mut vec_line = Vec::new();
        let pid_arr: Vec<i32> = value.extract().unwrap();
        for (index, val) in pid_arr.iter().enumerate() {
            if index <= pid_arr.len() - 2 {
                vec_line.push([
                    min(*val,pid_arr[index + 1]),
                    max(*val,pid_arr[index + 1])
                ])
            } else {
                vec_line.push([
                    min(*val,pid_arr[0]),
                    max(*val,pid_arr[0])
                ])
            }
        }
        // ➡️ 把点连接的数组作为引用key 找出只出现一次的
        for point_id_arr_as_key in vec_line.iter() {
            let [a,b] = *point_id_arr_as_key;
            let a_str = a.to_string();
            let b_str = b.to_string();
            // pointId1 + pointId2 自由边的两个点 + key是cellIndex
            let key = a_str + "#" + &b_str;
            match line_map.get(&key) {
                Some(val) => {
                    line_map.insert(key, [val[0] + 1,flag]);
                }
                None => { line_map.insert(key, [1,flag]); }
            }
        }
        flag+= 1;
    }
    // ➡️ 找出只出现一次的边
    for (key , value) in line_map.iter() {
        // 自由边
        if value[0] == 1 {
            result_free_edge.push(key.clone() + "#" + &value[1].to_string());
        }
        // 共享边
        if value[0] == 2 {
            result_share_edge.push(key.clone() + "#" + &value[1].to_string());
        }
        // T型边
        if value[0] >= 3 {
            result_t_edge.push(key.clone() + "#" + &value[1].to_string());
        }
    }
    let mut c = Vec::new();
    c.push(result_free_edge);
    c.push(result_share_edge);
    c.push(result_t_edge);
    c
}

#[pymodule]
fn RsFx(m: &Bound<'_, PyModule>) -> PyResult<()> {
    m.add_function(wrap_pyfunction!(sum_as_string, m)?)?;
    m.add_function(wrap_pyfunction!(test_res, m)?)?;
    m.add_function(wrap_pyfunction!(search_free_edge_cell, m)?)?;
    Ok(())
}
